﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    public class WorkQueues
    {
        public static void Producer(string[] args)
        {
            var factory = new ConnectionFactory { HostName = "supplier.xl24h.cn", Port = 5672, UserName = "admin", Password = "das@123!", VirtualHost = "/" };
            using var connection = factory.CreateConnection();
            using var channel = connection.CreateModel();

            // 设置队列、消息过期时间
            var arguments = new Dictionary<string, object>();
            // 队列30分钟后过期
            arguments.Add("x-expires", 1800000);
            // 消息1分钟后过期
            arguments.Add("x-message-ttl", 60000);
            channel.QueueDeclare(queue: "task_queue-ttl",
                                 durable: true, // 消息待久化
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: arguments);

            var message = GetMessage(args);
            var body = Encoding.UTF8.GetBytes(message);

            // 将消息标记为持久消息
            var properties = channel.CreateBasicProperties();
            properties.Persistent = true;

            channel.BasicPublish(exchange: string.Empty,
                                 routingKey: "task_queue-ttl",
                                 basicProperties: properties,
                                 body: body);
            Console.WriteLine($" [x] Sent {message}");

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }

        static string GetMessage(string[] args)
        {
            return ((args.Length > 0) ? string.Join(" ", args) : "Hello World!");
        }
    }
}
